package smedi.ismedi.web.bff.controller.pesonnel;

import com.smedi.ismedi.personnel.api.dto.response.ProfileImageResponse;
import com.smedi.ismedi.personnel.api.dto.response.SignatureResponse;
import com.smedi.ismedi.personnel.api.dto.response.UploadPersonTemplateValidateResponse;
import com.smedi.ismedi.personnel.api.feign.RemotePersonAssistFeignApi;
import com.smedi.ismedi.web.starter.common.ResponseData;
import com.smedi.ismedi.web.starter.exception.LogicException;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import smedi.ismedi.web.bff.controller.BaseController;
import smedi.ismedi.web.bff.infrastructure.constant.CustomError;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;

/**
 * 人员管理文件与定时接口
 *
 * @author xulinjun
 */
@Slf4j
@RestController
@Api(tags = {"人员管理文件与定时接口"})
@RequestMapping("/webbff/v1/personnelAssist")
@AllArgsConstructor
public class PersonAssistController extends BaseController {
    private final RemotePersonAssistFeignApi remotePersonAssistFeignApi;

    /**
     * 下载文件输出
     *
     * @param httpServletResponse
     * @param fileName
     * @param bytes
     * @throws IOException
     */
    private void writeHttpServletResponse(HttpServletResponse httpServletResponse, String fileName, byte[] bytes) throws IOException {
        httpServletResponse.reset();
        httpServletResponse.setContentType("application/x-download");
        httpServletResponse.addHeader("Content-Disposition", "attachment;filename=\"" + URLEncoder.encode(fileName, "UTF-8") + "\"");
        httpServletResponse.getOutputStream().write(bytes);
        httpServletResponse.getOutputStream().close();
    }

    /**
     * 上传人员头像照片
     *
     * @param file
     * @return
     */
    @ApiOperation(httpMethod = "POST", value = "上传人员头像照片")
    @PostMapping(value = "/uploadProfileImage")
    public ResponseData<String> postUploadProfileImage(@RequestPart("file") MultipartFile file) {
        return remotePersonAssistFeignApi.postUploadProfileImage(file);
    }

    /**
     * 下载人员头像照片
     *
     * @param imageUUID
     */
    @ApiOperation(httpMethod = "GET", value = "下载人员头像照片")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "query", name = "imageUUID", value = "照片id", dataType = "String", dataTypeClass = String.class)
    })
    @GetMapping(value = "/downloadProfileImage")
    public ResponseData<ProfileImageResponse> getDownloadProfileImage(@RequestParam("imageUUID") String imageUUID) throws IOException {
        return remotePersonAssistFeignApi.getDownloadProfileImage(imageUUID);
    }

    /**
     * 上传人员签章（不校验文件格式、文件大小）
     *
     * @param file
     * @return
     */
    @ApiOperation(httpMethod = "POST", value = "上传人员签章（不含校验文件格式、文件大小功能）")
    @PostMapping(value = "/uploadSignature")
    public ResponseData<String> postUploadSignature(@RequestPart("file") MultipartFile file) {
        return remotePersonAssistFeignApi.postUploadSignature(file);
    }

    /**
     * 下载人员签章
     *
     * @param signatureUUID
     */
    @ApiOperation(httpMethod = "GET", value = "下载人员签章")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "query", name = "signatureUUID", value = "签章id", dataType = "String", dataTypeClass = String.class)
    })
    @GetMapping(value = "/downloadSignature")
    public void getDownloadSignature(@RequestParam("signatureUUID") String signatureUUID, HttpServletResponse httpServletResponse) throws IOException {
        ResponseData<SignatureResponse> responseData = remotePersonAssistFeignApi.getDownloadSignature(signatureUUID);
        if (responseData.isSuccess()) {
            writeHttpServletResponse(httpServletResponse, responseData.getData().getFileName(), responseData.getData().getBytes());
        } else {
            throw LogicException.raise(CustomError.CALL_REMOTE_API_ERROR, responseData.getApplication(), String.valueOf(responseData.getErrorMsg()));
        }
    }

    /**
     * 根据人员id下载人员签章
     *
     * @param personId
     */
    @ApiOperation(httpMethod = "GET", value = "根据人员id下载人员签章")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "query", name = "personId", value = "人员id", dataType = "Long")
    })
    @GetMapping(value = "/downloadSignatureByPersonId")
    public void getDownloadSignatureByPersonId(@RequestParam("personId") Long personId, HttpServletResponse httpServletResponse) throws IOException {
        ResponseData<SignatureResponse> responseData = remotePersonAssistFeignApi.getDownloadSignatureByPersonId(personId);
        if (responseData.isSuccess()) {
            writeHttpServletResponse(httpServletResponse, responseData.getData().getFileName(), responseData.getData().getBytes());
        } else {
            throw LogicException.raise(CustomError.CALL_REMOTE_API_ERROR, responseData.getApplication(), String.valueOf(responseData.getErrorMsg()));
        }
    }

    /**
     * 人员信息导入
     *
     * @param file
     * @param organizationId
     * @param internal
     * @return
     * @throws IOException
     */
    @ApiOperation(httpMethod = "POST", value = "人员信息导入", notes = "导入项目人员时一定要传入projectId；如果是企业人员导入，则选择true，反之项目人员选择false；")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "query", name = "organizationId", value = "组织id", dataType = "Long", dataTypeClass = Long.class),
            @ApiImplicitParam(paramType = "query", name = "projectId", value = "项目id", dataType = "Long", dataTypeClass = Long.class),
            @ApiImplicitParam(paramType = "query", name = "internal", value = "是否企业人员", dataType = "Boolean", allowableValues = "true, false", dataTypeClass = Boolean.class),
    })
    @PostMapping(value = "/uploadPerson")
    public ResponseData<UploadPersonTemplateValidateResponse> postUploadPerson(@RequestPart("file") MultipartFile file,
                                                                               @RequestParam("organizationId") Long organizationId,
                                                                               @RequestParam(value = "projectId", required = false) Long projectId,
                                                                               @RequestParam("internal") boolean internal) throws IOException {
        return remotePersonAssistFeignApi.postUploadPerson(file, organizationId, projectId, internal);
    }

    /**
     * 确认校验交过并导入数据
     *
     * @param validateId
     * @return
     */
    @ApiOperation(httpMethod = "POST", value = "确认校验交过并导入数据")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "query", name = "validateId", value = "校验id", dataType = "String", dataTypeClass = String.class),
    })
    @PostMapping(value = "/confirmValidateAndSubmit")
    public ResponseData<UploadPersonTemplateValidateResponse> postConfirmValidateAndSubmit(@RequestParam("validateId") String validateId) {
        return remotePersonAssistFeignApi.postConfirmValidateAndSubmit(validateId);
    }

    /**
     * 从iMIS同步人员照片base64
     *
     * @param referencePersonId
     * @return
     */
    @ApiOperation(httpMethod = "GET", value = "从iMIS同步人员照片base64")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "query", name = "referencePersonId", value = "ERP人员id", dataType = "Long", dataTypeClass = Long.class),
    })
    @GetMapping(value = "/copyProfileImageBase64FromImis")
    public ResponseData<String> getCopyProfileImageBase64FromImis(@RequestParam("referencePersonId") Long referencePersonId) {
        return remotePersonAssistFeignApi.getCopyProfileImageBase64FromImis(referencePersonId);
    }

    /**
     * 从iMIS系统同步数据
     *
     * @return
     */
    @ApiOperation(httpMethod = "GET", value = "从iMIS系统同步数据")
    @GetMapping(value = "/syncFromImis")
    public ResponseData<Boolean> getSyncFromImis() {
        return remotePersonAssistFeignApi.getSyncFromImis();
    }

    /**
     * 开启定时同步任务
     *
     * @return
     */
    @ApiOperation(httpMethod = "GET", value = "开启定时同步任务")
    @GetMapping(value = "/startScheduleSync")
    public ResponseData<Boolean> getStartScheduleSync() {
        return remotePersonAssistFeignApi.getStartScheduleSync();
    }

    /**
     * 关闭定时同步任务
     *
     * @return
     */
    @ApiOperation(httpMethod = "GET", value = "关闭定时同步任务")
    @GetMapping(value = "/endScheduleSync")
    public ResponseData<Boolean> getEndScheduleSync() {
        return remotePersonAssistFeignApi.getEndScheduleSync();
    }
}
